using System.IO;
using System.Text;
using NUnit.Framework;
using Should;
using TLDRML;
using TLDRML.Nodes;

namespace TLDRMLTests
{
    public class XmlGeneratorVisitorContext
    {
        public string GenTest(IHasChildren parent)
        {
            var text = new StringBuilder();
            var xmlGen = new XmlGeneratorVisitor(new StringWriter(text));
            parent.Accept(xmlGen);
            return text.ToString();
        }
    }

    [TestFixture]
    public class XmlGeneratorVisitorTests : XmlGeneratorVisitorContext
    {
        [Test]
        public void Visit_SingleElementNode_WritesSingleXmlElement()
        {
            GenTest(new ElementNode("aa"))
                .ShouldEqual("<aa />");
        }

        [Test]
        public void Visit_NestElementNode_WritesNestedXmlElement()
        {
            GenTest(
                new ElementNode("aa",
                    new ElementNode("bb")))
                .ShouldEqual("<aa>\r\n  <bb />\r\n</aa>");
        }

        [Test]
        public void Visit_AttributeNode_WritesXmlAttributeNode()
        {
            var element = new ElementNode("aa");
            element.AddAttribute(new AttributeNode("bb","cc"));
            
            GenTest(element)
                .ShouldEqual("<aa bb=\"cc\" />");
        }

        [Test]
        public void IntegrationTest()
        {
            string input = GetType().Assembly.LoadResource("TLDRMLTests.Resources.Input.tldr");
            string expected = GetType().Assembly.LoadResource("TLDRMLTests.Resources.Expected.xml");

            DocNode doc = DocNode.LoadText(input);

            var result = new StringBuilder();
            var xmlGen = new XmlGeneratorVisitor(new StringWriter(result));
            doc.Accept(xmlGen);

            result.ToString().ShouldEqual(expected);
        }
    }
}